package com.authine.cloudpivot.ext.controller;

import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.enums.status.DataRowStatus;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.exception.PortalException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author hxd
 * @Date 2022/12/6 11:37
 * @Description
 **/
@Slf4j
@RequestMapping("/public/purchaseIntostorage")
@RestController
public class PurchaseIntostorageController extends BaseController {



    @PostMapping("/rkPassWc")
    public void rkPassWc(String bizId,String schemaCode,String subCode){

        if (StringUtils.isEmpty(bizId)) {
            throw new PortalException(-1L, "biz 不能为空");
        }

        if (StringUtils.isEmpty(subCode)) {
            throw new PortalException(-1L, "subCode 不能为空");
        }
        if (StringUtils.isEmpty(schemaCode)) {
            throw new PortalException(-1L, "schemaCode 不能为空");
        }

        BizObjectFacade bizObjectFacade = getBizObjectFacade();
        BizObjectCreatedModel model = bizObjectFacade.getBizObject(schemaCode, bizId);

        if (model == null || StringUtils.isEmpty( model.getId())) {
            throw new PortalException(-1L, String.format("数据不存在 bizId : %s ,schemaCode : %s ", bizId, schemaCode));
        }

        List<Map<String,Object>> list = (List<Map<String, Object>>) model.get(subCode);

        if (CollectionUtils.isEmpty(list)) {
            log.info("子表数据不存在,subCode={}",subCode);
            return;
        }
        Date now = new Date();

        List<Map<String, Object>> collect = list.stream().map(a -> {
            Map<String, Object> data = new HashMap<>();
            Date entryDate = (Date) a.get("entryDate");
            data.put("rkPassWc", entryDate.after(now) ? "是" : "否");
            data.put("rowStatus", DataRowStatus.Modified.name());
            data.put("id", a.get("id"));
            data.put("parentId", a.get("parentId"));
            return data;
        }).collect(Collectors.toList());

        BizObjectCreatedModel updateModel = new BizObjectCreatedModel(model.getSchemaCode(), new HashMap<>(), false);
        updateModel.put("id",bizId);
        updateModel.put(subCode,collect);

        bizObjectFacade.saveBizObject("2c9280a26706a73a016706a93ccf002b", updateModel, true);

    }

}
